#include "app_timer_process.h"
#include "app_timer_appsh.h"
#include "drv_audio.h"
#include "user_speech_recognition.h"

//定时器配置
#define APP_TIMER_PRESCALER              0   /**< Value of the RTC1 PRESCALER register. */
#define APP_TIMER_OP_QUEUE_SIZE          15  /**< Size of timer operation queues. */

APP_TIMER_DEF(wait_erase_timer_id);
APP_TIMER_DEF(m_melcep_process_timer_id);

APP_TIMER_DEF(print_audio_timer_id);

static void wait_erase_timer_handle(void *p_contex)
{
    //start_pdm_process_after_flash();
}

void app_timer_erase_callback(void)
{
    uint8_t err_code = 0;
    err_code = app_timer_start(wait_erase_timer_id,APP_TIMER_TICKS(1000,0),NULL);
}

static void app_timer_callback_reg()
{
    bool retb;
    // 定时器，用于擦除SPI_FLASH后，启动PDM
    retb = drv_audio_timer_erase_reg(app_timer_erase_callback);
}

void app_create_timer(uint8_t timer_index)
{
    uint32_t err_code = 0;
    switch(timer_index)
    {
        case APP_TIMER_MELCEP:
            err_code = app_timer_create(&m_melcep_process_timer_id,APP_TIMER_MODE_SINGLE_SHOT,mel_cep_event_process);
            APP_ERROR_CHECK(err_code);
            break;
        case 1:
            break;
        default:
            break;
    }
}

void app_start_timer(uint8_t timer_index)
{
    uint32_t err_code = 0;
    switch(timer_index)
    {
        case APP_TIMER_MELCEP:
            err_code = app_timer_start(m_melcep_process_timer_id,50,NULL);
            APP_ERROR_CHECK(err_code);
            break;
        case 1:
            break;
        default:
            break;
    }
}


#include "flash_data.h"

uint32_t audio_start_add;
int16_t *p_audio_add;
uint32_t audio_len = 0;
uint32_t audio_index = 0;

void start_print_audio_data(void)
{
    uint32_t err_code = 0;

    audio_len = CONFIG_AUDIO_FRAME_SIZE_SAMPLES / 2 * CONFIG_AUDIO_FRAME_TIMES;
    audio_start_add = flash_data_get_startADD();
    p_audio_add     = (int16_t*)audio_start_add;
    audio_index     = 0;

    err_code = app_timer_start(print_audio_timer_id,APP_TIMER_TICKS(5,0),NULL);
}

static void print_audio_timer_handle(void *p_contex)
{
    uint32_t err_code = 0;

    //start_pdm_process_after_flash();
    if(audio_index < audio_len)
    {
        NRF_UART_TRANSMIT("%d\n",p_audio_add[audio_index]);
    }
    else
    {
        NRF_UART_TRANSMIT("end\n");
        err_code = app_timer_stop(print_audio_timer_id);
    }

    audio_index++;
}

void app_timer_process_init(void)
{
    uint32_t err_code;

    // Initialize timer module.
    APP_TIMER_APPSH_INIT(APP_TIMER_PRESCALER, APP_TIMER_OP_QUEUE_SIZE, false);

    err_code = app_timer_create(&wait_erase_timer_id,APP_TIMER_MODE_SINGLE_SHOT,wait_erase_timer_handle);
    APP_ERROR_CHECK(err_code);
    
    err_code = app_timer_create(&print_audio_timer_id,APP_TIMER_MODE_REPEATED,print_audio_timer_handle);
    APP_ERROR_CHECK(err_code);
    
    app_timer_callback_reg();
}